package controller.user;


import ExceptionLogin.LoginFailedException;
import Message.DTO.UserLoginDTO;
import Message.Result;
import Message.entity.User;
import Message.vo.UserLoginVO;
import constant.JwtClaimsConstant;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import properties.JwtProperties;
import service.UserService;
import utils.JwtUtil;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户相关接口")
@Slf4j
@RequestMapping("/user/user")
@RestController
public class UserController {


@Autowired
UserService userService;
@Autowired
private JwtProperties jwtProperties;

/**
 *
 *微信小程序登录
 *
 */
 @PostMapping("/login")
 public Result login (@RequestBody UserLoginDTO dto) throws LoginFailedException {
     log.info("微信登录：dto={}",dto);

     //调用service 的登录方法获取
   User user  = userService.login(dto);


     // 2.如果登录成功，生成令牌jwt
     Map<String, Object> claims = new HashMap<>();
     claims.put(JwtClaimsConstant.USER_ID, user.getId());
     String token = JwtUtil.createJWT(
             jwtProperties.getUserSecretKey(),
             jwtProperties.getUserTtl(),
             claims);
     UserLoginVO userLoginVO = UserLoginVO.builder()
             .id(user.getId())
             .openid(user.getOpenid())
             .token(token)
             .build();
     return Result.success(userLoginVO);

 }
       @PostMapping("/logout")
       public Result logout() {
     log.info("用户退出成功");
        return Result.success();
       }

}
